<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @click="goBack">
        <text class="nav-icon">‹</text>
      </view>
      <view class="nav-center">
        <view class="nav-title">{{ chatUser.userName }}</view>
        <view class="online-status" :class="{ 'online': isOnline }">
          <text class="status-dot"></text>
          <text class="status-text">{{ isOnline ? '在线' : '离线' }}</text>
        </view>
      </view>
      <view class="nav-right">
        <text class="nav-icon">⋯</text>
        <text class="nav-icon">—</text>
        <text class="nav-icon">⊙</text>
      </view>
    </view>

    <!-- 商品信息卡片 -->
    <view class="product-card">
      <view class="product-image">
        <image src="/static/product-placeholder.jpg" class="product-img" mode="aspectFill"></image>
      </view>
      <view class="product-info">
        <view class="product-price">¥29.60</view>
        <view class="product-shipping">包运费0.00元</view>
        <view class="product-status">交易成功</view>
        <view class="product-guide">指南</view>
      </view>
      <view class="product-action">
        <button class="order-btn">订单详情</button>
      </view>
    </view>

    <!-- 消息列表（动态渲染：用户消息 / 系统提醒） -->
    <scroll-view class="message-list" scroll-y="true" :scroll-top="scrollTop" @scrolltoupper="loadOlder" :upper-threshold="50">
      <view class="message-item" v-for="message in messages" :key="message.id">
        <!-- 系统/订单提醒样式 -->
        <view v-if="message.type === 'system'" class="system-message">
          <view class="system-avatar">
            <image src="/static/system-avatar.jpg" class="avatar-img" mode="aspectFill"></image>
          </view>
          <view class="system-content">
            <view class="system-text">{{ message.content }}</view>
            <view class="system-time">{{ formatTime(message.timestamp) }}</view>
            <view v-if="message.notice" class="system-notice">{{ message.notice }}</view>
            <view v-if="message.tip" class="system-question">{{ message.tip }}</view>
          </view>
        </view>

        <!-- 普通用户消息样式 -->
        <view v-else class="message-wrapper" :class="{ 'my-message': message.isOwn }">
          <view class="avatar" v-if="!message.isOwn">
            <image :src="message.avatar || '/static/default-avatar.jpg'" class="avatar-img" mode="aspectFill"></image>
          </view>
          <view class="message-bubble" :class="{ 'my-bubble': message.isOwn }">
            <text>{{ message.content }}</text>
          </view>
          <view class="avatar" v-if="message.isOwn">
            <image src="/static/my-avatar.jpg" class="avatar-img" mode="aspectFill"></image>
          </view>
        </view>
        <view v-if="message.type !== 'system'" class="message-time">{{ formatTime(message.timestamp) }}</view>
      </view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view class="input-area">
      <view class="input-wrapper">
        <view class="input-left">
          <text class="input-icon">+</text>
        </view>
        <input 
          class="message-input" 
          v-model="inputMessage" 
          placeholder="说点什么..." 
          @confirm="sendMessage"
        />
        <view class="input-right">
          <text class="emoji-icon">😊</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import chatManager from '@/utils/chat.js'
import { appendMessage, getHistory } from '@/utils/chatStore.js'
import { fetchHistory, clearUnread } from '@/api/chat.js'

export default {
  data() {
    return {
      inputMessage: '',
      scrollTop: 0,
      messages: [],
      page: 1,
      limit: 50,
      hasMore: true,
      lastSentAt: 0,
      lastSentContent: '',
      // 聊天用户信息
      chatUser: {
        userId: '',
        userName: '磨砂小怪兽',
        avatar: '',
        productId: ''
      },
      currentUserId: '', // 当前登录用户ID
      messageHandlerId: null, // 消息监听器ID
      isOnline: false // 在线状态
    }
  },

  async onLoad(options) {
    // 接收从消息页面传递的参数
    if (options.userId) {
      this.chatUser.userId = options.userId
    }
    if (options.userName) {
      this.chatUser.userName = decodeURIComponent(options.userName)
    }
    if (options.avatar) {
      this.chatUser.avatar = decodeURIComponent(options.avatar)
    }
    if (options.productId) {
      this.chatUser.productId = options.productId
    }
    
    // 获取当前用户ID（从本地存储或全局状态获取）
	const userInfo = uni.getStorageSync('userInfo')
	
    this.currentUserId =userInfo.id;
    
    console.log('目标聊天用户信息:', this.chatUser)
    console.log('当前用户ID:', this.currentUserId)
    
    // 优先从后端加载第一页历史，失败则降级为本地
    if (this.currentUserId && this.chatUser.userId) {
      try {
        const serverHistory = await fetchHistory(this.currentUserId, this.chatUser.userId, this.page, this.limit)
        if (Array.isArray(serverHistory) && serverHistory.length) {
          this.messages = serverHistory.map(h => {
            const fromUser = h.from || h.From
            const toUser = h.to || h.To
            const ts = h.timestamp || h.Timestamp
            return {
              id: h.messageId || h.id || h.MessageId || `${(ts && new Date(ts).getTime()) || Date.now()}_${Math.random().toString(36).slice(2,8)}`,
              content: h.content || h.Content,
              timestamp: typeof ts === 'string' ? new Date(ts).getTime() : (ts || Date.now()),
              isOwn: fromUser === this.currentUserId,
              avatar: (fromUser === this.currentUserId) ? '' : this.chatUser.avatar,
              userName: (fromUser === this.currentUserId) ? '我' : this.chatUser.userName,
              type: ((h.type || h.Type || '').toLowerCase() === 'system' || fromUser === 'system') ? 'system' : 'user',
              from: fromUser,
              to: toUser
            }
          })
          this.hasMore = serverHistory.length === this.limit
        } else {
          const history = getHistory(this.currentUserId, this.chatUser.userId)
          this.messages = history.map(h => ({
            id: h.messageId || h.id,
            content: h.content,
            timestamp: h.timestamp,
            isOwn: h.from === this.currentUserId,
            avatar: (h.from === this.currentUserId) ? '' : this.chatUser.avatar,
            userName: (h.from === this.currentUserId) ? '我' : this.chatUser.userName,
            type: h.from === 'system' ? 'system' : 'user'
          }))
          this.hasMore = history.length >= this.limit
        }
        this.$nextTick(() => this.scrollToBottom())
      } catch (e) {
        const history = getHistory(this.currentUserId, this.chatUser.userId)
        this.messages = history.map(h => ({
          id: h.messageId || h.id,
          content: h.content,
          timestamp: h.timestamp,
          isOwn: h.from === this.currentUserId,
          avatar: (h.from === this.currentUserId) ? '' : this.chatUser.avatar,
          userName: (h.from === this.currentUserId) ? '我' : this.chatUser.userName,
          type: h.from === 'system' ? 'system' : 'user'
        }))
        this.hasMore = history.length >= this.limit
        this.$nextTick(() => this.scrollToBottom())
      }
    }

    // 初始化WebSocket连接（使用全局连接）
    await this.initWebSocket()
    
    // 清除与当前聊天对象的未读消息
    chatManager.clearUnreadMessages(this.chatUser.userId)
    try { await clearUnread(this.currentUserId, this.chatUser.userId) } catch (e) {}
    
    // 通知App更新未读消息计数
    const app = getApp()
    if (app && app.clearUnreadCount) {
      app.clearUnreadCount()
    }
  },

  onShow() {
    // 页面显示时滚动到底部
    this.$nextTick(() => {
      this.scrollToBottom()
    })
    
    // 设置应用为活跃状态
    chatManager.setAppActive(true)
  },

  onHide() {
    // 页面隐藏时设置应用为非活跃状态
    chatManager.setAppActive(false)
  },

  onUnload() {
    // 页面卸载时清理资源
    this.cleanup()
  },

  methods: {
    // 初始化WebSocket连接
    async initWebSocket() {
      try {
        // 注册消息监听器
        this.messageHandlerId = chatManager.onMessage(this.handleReceivedMessage)
        
        // 检查全局WebSocket连接状态
        if (!chatManager.getConnectionStatus()) {
          console.log('全局WebSocket未连接，尝试连接...')
          await chatManager.connect(this.currentUserId)
          console.log('WebSocket连接成功')
        } else {
          console.log('使用现有的全局WebSocket连接')
        }
        
        // 更新在线状态
        this.isOnline = chatManager.isConnected()
        
        // 监听连接状态变化
        this.connectionStatusHandler = (status) => {
          this.isOnline = status
        }
        this.connectionStatusListenerId = chatManager.onConnectionStatusChange(this.connectionStatusHandler)
        
        // 订阅聊天主题
        chatManager.subscribeToChatTopic(this.chatUser.userId, this.chatUser.productId)
        
      } catch (error) {
        console.error('WebSocket连接失败:', error)
        this.isOnline = false
        uni.showToast({
          title: '连接失败，请重试',
          icon: 'none'
        })
      }
    },

    // 处理接收到的消息
    handleReceivedMessage(message) {
      console.log('收到新消息:', message)
      
      // 只显示与当前聊天对象相关的消息
      // 消息必须是当前用户和聊天对象之间的对话
      if ((message.from === this.currentUserId && message.to === this.chatUser.userId) ||
          (message.from === this.chatUser.userId && message.to === this.currentUserId) ||
          (message.type && message.type.toLowerCase() === 'system')) {
        // 去重：优先用消息ID；如果缺失，则按(内容+时间戳+from+to)匹配
        const exists = this.messages.some(m => {
          if (m.id && message.messageId) return m.id === message.messageId
          return (
            m.content === message.content &&
            m.timestamp === message.timestamp &&
            (m.from || (m.isOwn ? this.currentUserId : this.chatUser.userId)) === message.from &&
            (m.to || (m.isOwn ? this.chatUser.userId : this.currentUserId)) === message.to
          )
        })
        if (exists) {
          return
        }

        this.messages.push({
          id: message.messageId,
          content: message.content,
          timestamp: message.timestamp,
          isOwn: message.from === this.currentUserId,
          avatar: message.from === this.currentUserId ? '' : this.chatUser.avatar,
          userName: message.from === this.currentUserId ? '我' : this.chatUser.userName,
          type: (message.type || '').toLowerCase() === 'system' ? 'system' : 'user'
        })
        
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })

        // 仅在对方发来的消息时写入本地历史（自发消息已在发送时写入）
        if (message.from !== this.currentUserId) {
          appendMessage(this.currentUserId, this.chatUser.userId, message)
        }
      }
    },

    // 发送消息
    async sendMessage() {
      if (!this.inputMessage.trim()) return
      
      try {
        // 简单防重复：800ms内同样内容不再发送
        const now = Date.now()
        const contentTry = this.inputMessage.trim()
        if (contentTry === this.lastSentContent && (now - this.lastSentAt) < 800) {
          return
        }
        this.lastSentContent = contentTry
        this.lastSentAt = now

        // 检查连接状态
        if (!chatManager.getConnectionStatus()) {
          uni.showToast({
            title: '连接已断开，正在重连...',
            icon: 'none'
          })
          await this.initWebSocket()
          return
        }
        
        const messageContent = contentTry
        
        // 发送消息
        const sentMessage = chatManager.sendMessage(
          this.chatUser.userId, 
          messageContent, 
          this.chatUser.productId
        )
        
		console.log("发生消息打印",sentMessage)
        // 添加到本地消息列表
        this.messages.push({
          id: sentMessage.messageId,
          content: messageContent,
          timestamp: sentMessage.timestamp,
          isOwn: true,
          avatar: '',
          userName: '我',
          type: 'user'
        })
        
        // 清空输入框
        this.inputMessage = ''
        
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })

        // 写入本地历史，保证消息列表与历史可见
        appendMessage(this.currentUserId, this.chatUser.userId, sentMessage)
        
      } catch (error) {
        console.error('发送消息失败:', error)
        uni.showToast({
          title: '发送失败，请重试',
          icon: 'none'
        })
      }
    },

    // 滚动到底部
    scrollToBottom() {
      this.scrollTop = 99999
    },

    // 清理资源
    cleanup() {
      console.log('清理聊天页面资源')
      
      // 移除消息监听器
      if (this.messageHandlerId) {
        chatManager.offMessage(this.messageHandlerId)
        this.messageHandlerId = null
      }
      
      // 移除连接状态监听器
      if (this.connectionStatusListenerId) {
        chatManager.removeConnectionStatusListener(this.connectionStatusListenerId)
        this.connectionStatusListenerId = null
      }
      
      // 注意：不在这里断开全局WebSocket连接，因为其他页面可能还在使用
    },

    // 加载更早的消息（滚到顶部触发）
    async loadOlder() {
      if (!this.hasMore) return
      try {
        const nextPage = this.page + 1
        const serverHistory = await fetchHistory(this.currentUserId, this.chatUser.userId, nextPage, this.limit)
        if (Array.isArray(serverHistory) && serverHistory.length) {
          const older = serverHistory.map(h => {
            const fromUser = h.from || h.From
            const toUser = h.to || h.To
            const ts = h.timestamp || h.Timestamp
            return {
              id: h.messageId || h.id || h.MessageId || `${(ts && new Date(ts).getTime()) || Date.now()}_${Math.random().toString(36).slice(2,8)}`,
              content: h.content || h.Content,
              timestamp: typeof ts === 'string' ? new Date(ts).getTime() : (ts || Date.now()),
              isOwn: fromUser === this.currentUserId,
              avatar: (fromUser === this.currentUserId) ? '' : this.chatUser.avatar,
              userName: (fromUser === this.currentUserId) ? '我' : this.chatUser.userName,
              type: ((h.type || h.Type || '').toLowerCase() === 'system' || fromUser === 'system') ? 'system' : 'user',
              from: fromUser,
              to: toUser
            }
          })
          this.messages = [...older, ...this.messages]
          this.page = nextPage
          if (serverHistory.length < this.limit) this.hasMore = false
        } else {
          this.hasMore = false
        }
      } catch (e) {
        this.hasMore = false
      }
    },

    // 格式化时间显示
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
      const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
      
      if (messageDate.getTime() === today.getTime()) {
        // 今天的消息只显示时间
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      } else {
        // 其他日期显示月-日 时:分
        return date.toLocaleString('zh-CN', { 
          month: '2-digit', 
          day: '2-digit', 
          hour: '2-digit', 
          minute: '2-digit' 
        })
      }
    },

    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  height: 88rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #e5e5e5;
}

.nav-left, .nav-right {
  display: flex;
  align-items: center;
}

.nav-center {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.nav-icon {
  font-size: 36rpx;
  color: #333333;
  margin-left: 16rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
}

/* 在线状态样式 */
.online-status {
  display: flex;
  align-items: center;
  margin-top: 4rpx;
}

.status-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: #ccc;
  margin-right: 8rpx;
}

.online .status-dot {
  background-color: #07c160;
}

.status-text {
  font-size: 24rpx;
  color: #999;
}

.online .status-text {
  color: #07c160;
}

/* 商品信息卡片 */
.product-card {
  background-color: #ffffff;
  padding: 24rpx 32rpx;
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #e5e5e5;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  margin-right: 24rpx;
}

.product-img {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.product-info {
  flex: 1;
}

.product-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4444;
  margin-bottom: 8rpx;
}

.product-shipping {
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 8rpx;
}

.product-status {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 8rpx;
}

.product-guide {
  font-size: 24rpx;
  color: #007aff;
}

.product-action {
  margin-left: 24rpx;
}

.order-btn {
  background-color: #ffeb3b;
  color: #333333;
  border: none;
  border-radius: 40rpx;
  padding: 16rpx 32rpx;
  font-size: 28rpx;
}

/* 消息列表 */
.message-list {
  flex: 1;
  padding: 24rpx 32rpx;
}

/* 黄色提醒消息 */
.reminder-message {
  background-color: #ffeb3b;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  position: relative;
}

.reminder-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 16rpx;
}

.reminder-text {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.5;
}

.reminder-time {
  position: absolute;
  bottom: 16rpx;
  right: 24rpx;
  font-size: 24rpx;
  color: #999999;
}

/* 发货提醒 */
.ship-reminder {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 24rpx;
}

.ship-btn {
  background-color: #ffeb3b;
  color: #333333;
  border-radius: 40rpx;
  padding: 16rpx 32rpx;
  font-size: 28rpx;
  margin-right: 16rpx;
}

.ship-time {
  font-size: 24rpx;
  color: #999999;
}

/* 付款提醒 */
.payment-notice {
  text-align: center;
  padding: 16rpx;
  margin-bottom: 24rpx;
}

.payment-notice text {
  font-size: 24rpx;
  color: #999999;
}

/* 普通消息 */
.message-item {
  margin-bottom: 32rpx;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
}

.message-wrapper.my-message {
  flex-direction: row-reverse;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  margin: 0 16rpx;
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.message-bubble {
  max-width: 480rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  position: relative;
}

.message-bubble.my-bubble {
  background-color: #007aff;
  color: #ffffff;
}

.message-time {
  text-align: center;
  font-size: 24rpx;
  color: #999999;
  margin-top: 8rpx;
}

/* 系统消息 */
.system-message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 32rpx;
}

.system-avatar {
  width: 80rpx;
  height: 80rpx;
  margin-right: 16rpx;
}

.system-content {
  flex: 1;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
}

.system-text {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.5;
  margin-bottom: 16rpx;
}

.system-time {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 16rpx;
}

.system-notice {
  font-size: 24rpx;
  color: #ff4444;
  margin-bottom: 16rpx;
}

.system-question {
  font-size: 24rpx;
  color: #999999;
}

/* 底部输入区域 */
.input-area {
  background-color: #ffffff;
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #e5e5e5;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 48rpx;
  padding: 16rpx 24rpx;
}

.input-left, .input-right {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-icon {
  font-size: 32rpx;
  color: #666666;
}

.emoji-icon {
  font-size: 32rpx;
}

.message-input {
  flex: 1;
  background-color: transparent;
  border: none;
  font-size: 28rpx;
  color: #333333;
  margin: 0 16rpx;
}

.message-input::placeholder {
  color: #999999;
}
</style>